<template>
  <div class="flex">
    <el-card :gutter="12" class="w-1/2" shadow="always">
      <template #header>
        <div class="card-header">
          <span>连 接</span>
        </div>
      </template>
      <div class="flex items-center">
        <span class="text-lg font-medium mr-4"> 连接状态: </span>
        <el-tag>{{ status }}</el-tag>
      </div>
      <hr class="my-4" />

      <div class="flex">
        <el-input v-model="server">
          <template #prepend> 服务地址</template>
        </el-input>
        <el-button type="primary" @click="submit"> 开启连接 </el-button>
      </div>

      <p class="text-lg font-medium mt-4">发送消息</p>
      <hr class="my-4" />
      <el-input
        v-model="sendValue"
        :autosize="{ minRows: 2, maxRows: 4 }"
        clearable
        type="textarea"
      />
      <el-button block class="mt-4" type="primary"> 发 送 </el-button>
    </el-card>
    <el-card :gutter="12" class="w-1/2" shadow="always">
      <template #header>
        <div class="card-header">
          <span>消息记录</span>
        </div>
      </template>
      <div class="max-h-80 overflow-auto">
        <ul>
          <li v-for="(item, index) in data" :key="index" class="mt-2">
            <div class="flex items-center">
              <span class="mr-2 text-primary font-medium">收到消息:</span>
              <span>{{ item }}</span>
            </div>
          </li>
        </ul>
      </div>
    </el-card>
  </div>
</template>
<script lang="ts" name="InfraWebSocket" setup>
const server = ref('')
const status = ref('未连接')
const sendValue = ref('')

const dataFormat = ref([])

const data = ref([])

let socket: any = null

const submit = () => {
  socket = null

  socket = new WebSocket(server.value)

  socket.onopen = function () {
    status.value = '已连接'
  }

  socket.onmessage = function (evt) {
    data.value.push(evt.data)
  }

  socket.onclose = function () {
    status.value = '未连接'
  }
}
</script>
